<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\ProductStatus;
use App\Enums\ShippingStatus;
use App\Exports\EntityApplyExport;
use App\Http\Controllers\Controller;
use App\Jobs\DownloadsJob;
use App\Models\AgentUser;
use App\Models\Download;
use App\Models\EntityApplyRecord;
use App\Models\RightsEntity;
use App\Models\RightsEntityProduct;
use App\Utils\UploadHelper;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Throwable;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;
use Vinlon\Laravel\LayAdmin\PaginateResponse;

class RightsEntityController extends Controller
{
    /**
     * 实物商品列表.
     */
    public function list(): PaginateResponse
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $query = RightsEntity::query()->where('agent_id', $user->agent_id)
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';

                return $q->where('name', 'like', $likeVal);
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /**
     * 保存实物.
     */
    public function store()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $params = request()->validate([
            'name' => 'required',
            'logo_url' => 'required',
            'description' => 'nullable',
        ]);

        /** @var RightsEntity $entity */
        $entity = get_entity(RightsEntity::class);
        $entity->agent_id = $user->agent_id;
        $entity->fill($params);
        $entity->save();
    }

    /**
     * 暂停实物.
     *
     * @param $id
     *
     * @throws AdminException
     */
    public function pauseEntity($id)
    {
        /** @var RightsEntity $entity */
        $entity = RightsEntity::query()->find($id);
        if (!$entity) {
            throw new AdminException('数据不存在');
        }
        $entity->status = ProductStatus::PAUSE;
        $entity->save();
    }

    /**
     * 发行实物.
     *
     * @param $id
     *
     * @throws AdminException
     */
    public function saleEntity($id)
    {
        /** @var RightsEntity $entity */
        $entity = RightsEntity::query()->find($id);
        if (!$entity) {
            throw new AdminException('数据不存在');
        }
        $entity->status = ProductStatus::ON_SALE;
        $entity->save();
    }

    /**
     * 删除实物.
     *
     * @param $id
     *
     * @throws AdminException
     */
    public function destroy($id)
    {
        /** @var RightsEntity $entity */
        $entity = RightsEntity::query()->find($id);
        if (!$entity) {
            throw new AdminException('数据不存在');
        }

        if (RightsEntityProduct::query()->where('entity_id', $id)->exists()) {
            throw new AdminException('实物已被商品关联不能删除.');
        }
        if (EntityApplyRecord::query()->where('entity_id', $id)->exists()) {
            throw new AdminException('存在申请记录不能删除.');
        }

        RightsEntity::destroy($id);
    }

    /**
     * 实物申请记录.
     */
    public function applyRecords(): PaginateResponse
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $query = EntityApplyRecord::query()->where('agent_id', $user->agent_id)
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';
                $q->whereHas('user', function ($q1) use ($likeVal) {
                    return $q1->where('mobile', 'like', $likeVal)->orWhere('nickname', 'like', $likeVal);
                });
            })
            ->when(request()->name, function ($q) {
                $likeVal = '%' . request()->name . '%';
                $q->whereHas('entity', function ($q1) use ($likeVal) {
                    return $q1->where('name', 'like', $likeVal);
                });
            })
            ->when(request()->status, function ($q) {
                return $q->where('status', request()->status);
            })
            ->when(request()->start_date, function ($q) {
                return $q->where('created_at', '>=', request()->start_date);
            })
            ->when(request()->end_date, function ($q) {
                return $q->where('created_at', '<=', request()->end_date);
            })
            ->with(['user', 'entity', 'product'])
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /**
     * 编辑申请记录.
     */
    public function editApplyRecords()
    {
        $params = request()->validate([
            'express_name' => 'nullable',
            'logistics_no' => 'nullable',
        ]);

        /** @var RightsEntity $entity */
        $entity = get_entity(EntityApplyRecord::class);

        if (empty($params['express_name']) && empty($params['logistics_no'])) {
            $entity->status = ShippingStatus::UNSHIPPED;
        } else {
            $entity->status = ShippingStatus::SHIPPED;
        }

        $entity->fill($params);
        $entity->save();
    }

    /**
     * 批量更新发货状态
     *
     * @throws AdminException
     * @throws Throwable
     */
    public function batchEditApplyRecords()
    {
        $data = request()->all();

        /** @var AgentUser $user */
        $user = auth()->user();

        DB::transaction(function () use ($data, $user) {
            foreach ($data['express_name'] as $k => $v) {
                if ((empty($v) && !empty($data['logistics_no'][$k])) || (!empty($v) && empty($data['logistics_no'][$k]))) {
                    throw new AdminException('快递名称和物流单号必须同时存在');
                }

                /** @var RightsEntity $entity */
                $entity = EntityApplyRecord::query()->where('agent_id', $user->agent_id)->find($data['id'][$k]);

                if (!$entity) {
                    throw new AdminException('申请记录不存在');
                }
                if (empty($v) && empty($data['logistics_no'][$k])) {
                    $entity->status = ShippingStatus::UNSHIPPED;
                } else {
                    $entity->status = ShippingStatus::SHIPPED;
                }
                $entity->fill([
                    'logistics_no' => $data['logistics_no'][$k],
                    'express_name' => $v,
                ]);
                $entity->save();
            }
        });
    }

    /**
     * 兑付申请记录导出.
     */
    public function applyExport()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $file = '兑付申请' . date('YmdHis') . uniqid() . '.xls';

        $download = Download::create([
            'agent_id' => $user->agent_id,
            'user_id' => $user->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => EntityApplyExport::class,
            'request' => json_encode(request()->all()),
        ]);

        dispatch(new DownloadsJob($download));
    }

    /**
     * @throws Exception
     *
     * @return mixed
     */
    public function import(Request $request)
    {
        $isFile = $request->hasFile('file');
        if (!$isFile) {
            throw new Exception('请上传文件');
        }
        $data = UploadHelper::readExcel($request->file('file'));
        unset($data[0]);

        return $data;
    }
}
